'use strict';
require("./requires");
var crypto = require('../utils/crypto');
var express = require('express');
var db = require('../utils/db');
var http = require("../utils/http");
var app = express();
var configs = require(process.argv[2]);
db.init(configs.mysql());
var config = configs.account_server();
app.listen(config.CLIENT_PORT);
var hallAddr = config.HALL_IP + ":" + config.HALL_CLIENT_PORT;
var goldHallAddr = "http://" + config.HALL_IP + ":" + config.GOLD_HALL_CLIENT_PORT;
var _ = require("lodash");

var log4js = require('log4js');
var path = require('path');

var logConfig = require('./config/log4js')
log4js.configure(logConfig(path.dirname(__dirname)));
var log = log4js.getLogger("accountServer");
var generate_num_control = 0;
function send(res, ret) {
	var str = JSON.stringify(ret);
	res.send(str);
	log.debug(str);
}

app.use(log4js.connectLogger(log4js.getLogger("httpAccess"), { level: 'auto' }));
//设置跨域访问
app.all('*', function (req, res, next) {
	res.header("Access-Control-Allow-Origin", "*");
	res.header("Access-Control-Allow-Headers", "X-Requested-With");
	res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
	res.header("X-Powered-By", ' 3.2.1')
	res.header("Content-Type", "application/json;charset=utf-8");
	next();
});

app.get('/register', function (req, res) {
	var account = req.query.account;
	var password = req.query.password;

	var fnFailed = function () {
		send(res, { errcode: 1, errmsg: "account has been used." });
	};

	var fnSucceed = function () {
		send(res, { errcode: 0, errmsg: "ok" });
	};

	db.is_user_exist(account, function (userid, exist) {
		if (exist) {
			db.create_account(account, password, function (ret) {
				if (ret) {
					fnSucceed();
				}
				else {
					fnFailed();
				}
			});
		}
		else {
			log.warn("account has been used.");
			fnFailed();

		}
	});
});

var VERSION = 20161204;

app.get('/get_version', function (req, res) {
	var ret = {
		version: VERSION,
	}
	send(res, ret);
});

app.get('/guest', function (req, res) {
	//var account = "guest_" + req.query.account;
	var account = req.query.account;
	var sign = crypto.md5(account + req.ip + config.ACCOUNT_PRI_KEY);
	var ret = {
		errcode: 0,
		errmsg: "ok",
		account: account,
		halladdr: hallAddr,     //房卡麻将大厅服地址
		goldHallAddr: goldHallAddr,  //金币麻将大厅服地址
		sign: sign
	}
	send(res, ret);
});

//获取url请求客户端ip
function get_client_ip(req) {
    var ip = req.headers['x-forwarded-for'] ||
        req.ip ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection.socket.remoteAddress || '';
    if(ip.split(',').length>0){
        ip = ip.split(',')[0];
    }
    if(ip.split(':').length>0){
        ip = ip.split(':')[3];
    }
    return ip;
};

app.get('/auth', function (req, res) {
	var account = req.query.account;
	var password = req.query.password;

	db.get_account_info(account, password, function (info) {
		if (info == null) {
			send(res, { errcode: 1, errmsg: "invalid account" });
			return;
		}

		var account = "vivi_" + req.query.account;
		var sign = get_md5(account + req.ip + config.ACCOUNT_PRI_KEY);
		var ret = {
			errcode: 0,
			errmsg: "ok",
			account: account,
			sign: sign
		}
		send(res, ret);
	});
});

var appInfo = {
	Android: {
		appid: "wxd11f8bb5319188d3",   //wx7760c467ec57d20d 新的 wxe39f08522d35c80c 原来的   wxc96d40d6ed3cfd7e
		secret: "673224e425deb51241855b5ec5d59070", // 7c55a72926d3c6b0d96501bcd3285c8e 新的 fa88e3a3ca5a11b06499902cea4b9c01 原来的
	},
	iOS: {
		appid: "wxd11f8bb5319188d3",  //wx7760c467ec57d20d 新的 wxcb508816c5c4e2a4 原来的
		secret: "673224e425deb51241855b5ec5d59070",	//7c55a72926d3c6b0d96501bcd3285c8e 新的 7de38489ede63089269e3410d5905038	原来的 12e62639e87a910bf03cbb44311ad5b4
	}
};

function get_access_token(code, os, callback) {
	var info = appInfo[os];
	if (info == null) {
		callback(false, null);
	}
	var data = {
		appid: info.appid,
		secret: info.secret,
		code: code,
		grant_type: "authorization_code"
	};

	http.get2("https://api.weixin.qq.com/sns/oauth2/access_token", data, callback, true);
}

app.get('/get_serverinfo', function (req, res) {
	var devType = req.query.device;
	var webAddr = "";
	log.debug("receive type == " + devType);
	if ("android" == devType) {
		webAddr = "http://www.yp6868.com";
	}
	else if ("ios" == devType) {
		log.debug("receive type 2 == " + devType);
		webAddr = "http://www.yp6868.com";
	}
	else {
		webAddr = "http://www.yp6868.com";
	}
	log.debug(webAddr);
	var ret = {
		version: VERSION,
		hall: hallAddr,
		goldHallAddr: goldHallAddr,  //金币麻将大厅服地址
		appweb: webAddr,
	}
	send(res, ret);
});

function get_state_info(access_token, openid, callback) {
	var data = {
		access_token: access_token,
		openid: openid
	};

	http.get2("https://api.weixin.qq.com/sns/userinfo", data, callback, true);
}

function generateUserId() {
	var userId = "";
	for (var i = 0; i < 6; ++i) {
		if (i == 0) {
			userId = 1 + Math.floor(Math.random() * 9);
		}
		else {
			userId += (Math.floor(Math.random() * 10)).toString();
		}
	}
	return userId;
}

function generateOnlyUserId(account, name, coins, gems, sex, headimgurl, ip, callback) {
	++generate_num_control;
	if (generate_num_control > 2) {
		callback(0, false);
	}
	var userId = generateUserId();
	db.is_userid_exist(userId, function (data) {
		if (data == 0) {
			db.create_user(userId, account, name, coins, gems, sex, headimgurl, ip, function (ret1, ret2) {
				callback(ret1, ret2);
			});
		}
		else {
			log.debug("repeat generate user id!");
			generateOnlyUserId(account, name, coins, gems, sex, headimgurl, ip, function (ret1, ret2) {
				callback(ret1, ret2);
			});
		}
	});
}

function create_user(account, name, sex, headimgurl, ip, callback) {
	var coins = 50000;
	var gems = 18;
	db.is_user_exist(account, function (userid, ret) {
		if (!ret) {
			generateOnlyUserId(account, name, coins, gems, sex, headimgurl, ip, function (ret1, ret2) {
				callback(ret1, ret2);
			});
		}
		else {
			db.update_user_info(account, name, headimgurl, sex, function (ret2) {
				callback(userid, ret2);
			});
		}
	});
};
app.get('/wechat_auth', function (req, res) {
	var code = req.query.code;
	var os = req.query.os;
	log.debug("account receive wechat_auth, code == " + code);
	if (code == null || code == "" || os == null || os == "") {
		return;
	}
	log.debug("account receive wechat_auth, os == " + os);
	if (req.query.version == null) {
		send(res, { errcode: -7, errmsg: "为了您更好体验我们的产品,请您到微信公众号“有朋棋牌”下载最新版本进行安装!", size: 14 });
		return;
	}

	db.getGameInfo(function (retVal) {
		if (retVal != null) {
			if (_.isString(req.query.version) && _.isString(retVal.version)) {
				var query_client = req.query.version.split(".");
				var query_server = retVal.version.split(".");
				if (query_client.length < query_server.length) {
					send(res, { errcode: -7, errmsg: "为了您更好体验我们的产品,请您到微信公众号“有朋棋牌”下载最新版本进行安装!", size: 14 });
					return;
				}
				if (query_server != null && query_client.length == query_server.length) {
					for (let i = 0; i < query_client.length; ++i) {
						var clientVer = Number.parseInt(query_client[i]);
						var serverVer = Number.parseInt(query_server[i]);
						if (clientVer < serverVer) {
							send(res, { errcode: -7, errmsg: "为了您更好体验我们的产品,请您到微信公众号“有朋棋牌”下载最新版本进行安装!", size: 14 });
							return;
						} else if (clientVer > serverVer) {
							break;
						}
					}
				}
			}
		}
		generate_num_control = 0;
		var appWeb = "http://www.yp6868.com";
		get_access_token(code, os, function (suc, data) {
			if (suc) {
				var access_token = data.access_token;
				var openid = data.openid;
				get_state_info(access_token, openid, function (suc2, data2) {
					if (suc2) {
						if (data2.openid === undefined) {
							send(res, { errcode: -6, errmsg: "微信授权失败,请重新登陆游戏,再次授权微信登陆!" });
							return;
						}

						var openid = data2.openid;
						var nickname = data2.nickname;
						var sex = data2.sex;
						var headimgurl = data2.headimgurl;
						var account = "wx_" + openid;
						var ip = get_client_ip(req);
						log.debug("new user wei xin name ip == " + data2.nickname + ip);

						create_user(account, nickname, sex, headimgurl, ip, function (ret1, ret2) {
							if (ret2 == true) {
								var sign = crypto.md5(account + ip + config.ACCOUNT_PRI_KEY);
								send(res, {
									errcode: 0,
									errmsg: "ok",
									account: account,
									halladdr: hallAddr,     //房卡麻将大厅服地址
									goldHallAddr: goldHallAddr,  //金币麻将大厅服地址
									sign: sign,
									name: nickname,
									sex: sex,
									headimgurl: headimgurl,
									userid: ret1,
									appweb: appWeb
								});

								log.debug("wechat_auth create user success!");
								log.debug(" userid == " + ret1 + " account == " + account + " headimgurl == " + headimgurl);
							}
							else {
								log.warn("create user failed!");
								send(res, { errcode: -6, errmsg: "微信授权失败,请重新登陆游戏,再次授权微信登陆!" });
							}
						});
					}
				});
			}
			else {
				log.warn("create user failed! unknown error");
				send(res, { errcode: -1, errmsg: "unkown err." });
			}
		});
	});

});

app.get('/base_info', function (req, res) {
	var userid = req.query.userid;
	db.get_user_base_info(userid, function (data) {
		if (data != null) {
			var ret = {
				errcode: 0,
				errmsg: "ok",
				name: data.name,
				sex: data.sex,
				headimgurl: data.headimg
			};
			send(res, ret);
			log.debug("get base info success!");
			log.debug(ret);
		}
		else {
			log.warn("get base info no user data error");
			send(res, { errcode: -1, errmsg: "no user data." });
		}
	});
});

app.get('/get_message', function (req, res) {
	// if (!check_account(req, res)) {
	// 	return;
	// }
	var type = req.query.type;

	if (type == null) {
		http.send(res, -1, "parameters don't match api requirements.");
		return;
	}

	var version = req.query.version;
	var version2 = '99.99.99';
	db.get_message(type, version2, function (data) {
		if (data != null) {
			if (_.isString(version) && _.isString(data.version)) {
				var query_client = version.split(".");
				var query_server = data.version.split(".");
				if (query_client.length < query_server.length) {
					http.send(res, 0, "ok", { msg: data.msg, version: data.version, isdownload: true });
					return;
				}
				if (query_server != null && query_client.length == query_server.length) {
					for (let i = 0; i < query_client.length; ++i) {
						var clientVer = Number.parseInt(query_client[i]);
						var serverVer = Number.parseInt(query_server[i]);
						if (clientVer < serverVer) {
							http.send(res, 0, "ok", { msg: data.msg, version: data.version, isdownload: true });
							return;
						} else if (clientVer > serverVer) {
							break;
						}
					}
				}
			}
			http.send(res, 0, "ok", { msg: data.msg, version: data.version, isdownload: false });
		}
		else {
			http.send(res, 1, "get message failed.");
		}
	});
});

log.info("account server is listening on port " + config.CLIENT_PORT);